package com.example.wzdjcrdpassword.controller;

import com.example.wzdjcrdpassword.entity.UserReport;
import com.example.wzdjcrdpassword.service.UserReportService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户数据上报控制器
 */
@RestController
@RequestMapping("/api/user-report")
@Slf4j
@RequiredArgsConstructor
public class UserReportController {
    
    private final UserReportService userReportService;
    
    /**
     * 用户数据上报接口
     */
    @PostMapping("/submit")
    public ResponseEntity<Map<String, Object>> submitUserReport(
            @RequestBody Map<String, Object> requestData) {
        
        log.info("接收到用户数据上报请求: {}", requestData);
        
        // 验证必填字段
        if (!requestData.containsKey("macAddress")) {
            return ResponseEntity.badRequest().body(createErrorResponse("缺少必填字段: macAddress"));
        }
        
        String macAddress = (String) requestData.get("macAddress");
        String accountInfo = getJsonString(requestData.get("accountInfo"));
        String heroInfo = getJsonString(requestData.get("heroInfo"));
        String otherInfo = getJsonString(requestData.get("otherInfo"));
        
        // 验证MAC地址格式
        if (!userReportService.validateMacAddress(macAddress)) {
            return ResponseEntity.badRequest().body(createErrorResponse("MAC地址格式不正确"));
        }
        
        // 验证JSON数据格式
        if (!userReportService.validateJsonData(accountInfo)) {
            return ResponseEntity.badRequest().body(createErrorResponse("账号信息JSON格式不正确"));
        }
        
        if (!userReportService.validateJsonData(heroInfo)) {
            return ResponseEntity.badRequest().body(createErrorResponse("英雄信息JSON格式不正确"));
        }
        
        if (!userReportService.validateJsonData(otherInfo)) {
            return ResponseEntity.badRequest().body(createErrorResponse("其他信息JSON格式不正确"));
        }
        
        try {
            // 创建数据上报记录
            UserReport userReport = userReportService.createUserReport(macAddress, accountInfo, heroInfo, otherInfo);
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "数据上报成功");
            response.put("businessId", userReport.getBusinessId());
            response.put("createTime", userReport.getCreateTime());
            
            log.info("用户数据上报成功，MAC地址: {}, 业务ID: {}", macAddress, userReport.getBusinessId());
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("用户数据上报失败，MAC地址: {}", macAddress, e);
            return ResponseEntity.internalServerError().body(createErrorResponse("数据上报失败: " + e.getMessage()));
        }
    }
    
    /**
     * 根据业务ID查询数据上报记录
     */
    @GetMapping("/{businessId}")
    public ResponseEntity<Map<String, Object>> getUserReport(@PathVariable String businessId) {
        UserReport userReport = userReportService.getUserReportByBusinessId(businessId);
        
        if (userReport == null || "YES".equals(userReport.getIsDeleted())) {
            return ResponseEntity.notFound().build();
        }
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", convertToResponse(userReport));
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 根据MAC地址查询数据上报记录
     */
    @GetMapping("/mac/{macAddress}")
    public ResponseEntity<Map<String, Object>> getUserReportsByMacAddress(@PathVariable String macAddress) {
        List<UserReport> userReports = userReportService.getUserReportsByMacAddress(macAddress);
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", userReports.stream().map(this::convertToResponse).toList());
        response.put("total", userReports.size());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 查询所有有效的数据上报记录
     */
    @GetMapping("/all")
    public ResponseEntity<Map<String, Object>> getAllActiveReports() {
        List<UserReport> userReports = userReportService.getAllActiveReports();
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("data", userReports.stream().map(this::convertToResponse).toList());
        response.put("total", userReports.size());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 逻辑删除数据上报记录
     */
    @DeleteMapping("/{businessId}")
    public ResponseEntity<Map<String, Object>> deleteUserReport(@PathVariable String businessId) {
        boolean deleted = userReportService.deleteUserReport(businessId);
        
        Map<String, Object> response = new HashMap<>();
        if (deleted) {
            response.put("success", true);
            response.put("message", "数据上报记录删除成功");
            return ResponseEntity.ok(response);
        } else {
            response.put("success", false);
            response.put("message", "数据上报记录不存在或已被删除");
            return ResponseEntity.notFound().build();
        }
    }
    
    /**
     * 将对象转换为JSON字符串
     */
    private String getJsonString(Object obj) {
        if (obj == null) {
            return null;
        }
        
        if (obj instanceof String) {
            return (String) obj;
        }
        
        // 如果是Map或其他对象，可以转换为JSON字符串
        // 这里简单处理，实际项目中可以使用Jackson等库
        return obj.toString();
    }
    
    /**
     * 创建错误响应
     */
    private Map<String, Object> createErrorResponse(String message) {
        Map<String, Object> errorResponse = new HashMap<>();
        errorResponse.put("success", false);
        errorResponse.put("message", message);
        return errorResponse;
    }
    
    /**
     * 将UserReport转换为响应格式
     */
    private Map<String, Object> convertToResponse(UserReport userReport) {
        Map<String, Object> response = new HashMap<>();
        response.put("businessId", userReport.getBusinessId());
        response.put("macAddress", userReport.getMacAddress());
        response.put("accountInfo", userReport.getAccountInfo());
        response.put("heroInfo", userReport.getHeroInfo());
        response.put("otherInfo", userReport.getOtherInfo());
        response.put("createTime", userReport.getCreateTime());
        response.put("updateTime", userReport.getUpdateTime());
        return response;
    }
}